<!--
 * @Author: pengyong
 * @LastEditors: pengyong
 * @Description: 国外省市区选择器
-->
<template>
  <el-cascader
    ref="cascad"
    v-model="selectedOptions"
    :disabled="disabled"
    :options="options"
    :props="props"
    :placeholder="hasDafaultValue ? `${defaultProps.country}/${defaultProps.province}` : '请选择'"
    clearable
    :class="['area-select', hasDafaultValue && 'active']"
    style="width: 300px;"
    @active-item-change="handleItemChange"
    @change="handleChange"
  />
</template>

<script>
import { getDictDetail, getEqpttype } from '@/api/common'
/**
 * defaultProps: 回显值，格式{ country: '', province: '' }
 * disabled: 是否禁用
 * 国外地区只有两成结构
 */
export default {
  props: {
    defaultProps: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: [],
      selectedOptions: [],
      props: {
        label: 'name',
        value: 'id',
        lazy: true,
        lazyLoad: this.lazyLoad
      }
    }
  },
  computed: {
    hasDafaultValue() {
      return this.defaultProps && this.defaultProps.country
    }
  },
  watch: {
    selectedOptions(arr) {
      this.handleItemChange(arr)
    }
  },
  mounted() {
    this.countryIndex = -1
    this.provinceIndex = -1
    this.cityIndex = -1
    this.countryItem = {}
    this.provinceItem = {}
    this.cityItem = {}
    this.areaItem = {}
    getDictDetail().then(res => {
      this.options = res.content.map(item => ({ ...item, name: item.label, children: [] }))
    })
  },
  methods: {
    clear() {
      this.selectedOptions = []
    },
    handleItemChange(arr) {
      const [countryId, provinceId] = arr
      if (countryId) {
        this.countryIndex = this.options.findIndex(item => item.id === countryId)
        this.countryItem = this.options[this.countryIndex]
      }
      if (provinceId) {
        this.provinceIndex = this.options[this.countryIndex].children.findIndex(item => item.id === provinceId)
        this.provinceItem = this.options[this.countryIndex].children[this.provinceIndex]
      }
      switch (arr.length) {
        case 1:
          // 获取省份数据
          getEqpttype(countryId).then(res => {
            this.options[this.countryIndex].children = res.content.map(item => ({ ...item }))
          })
          break;
      }
    },
    handleChange(arr) {
      const provinceId = arr[arr.length - 1]
      if (provinceId) {
        this.provinceItem = this.options[this.countryIndex].children.find(item => item.id === provinceId)
        this.$emit('change', this.countryItem, this.provinceItem, this.cityItem, this.areaItem)
      }
    }
  }
}
</script>

<style lang="scss">
.area-select {
  &.active {
    .el-input {
        .el-input__inner::placeholder {
            color: #606266;
        }
        .el-input__inner::-webkit-input-placeholder {
            color: #606266;
        }
    }
  }
}
</style>
